<?php

namespace App\Http\Controllers;

use App\Custom\Api\ApiResponse;
use App\Exceptions\AuthNoPermissionException;
use App\Models\User;
use ReflectionClass;
use ReflectionException;

class ApiController extends Controller
{
    use ApiResponse;

    /**
     * include 引入内容
     *
     * @param $model
     * @return mixed
     */
    public function includeLoad($model)
    {
        // 获取request的内容
        $includesString = request()->get('include');
        if (!$includesString || !$model) {
            return $model;
        }
        $includes = explode(',', $includesString);
        // load预加载
        $model->load($includes);
        return $model;
    }


    /**
     * 获取当前请求用户
     *
     * @return User
     */
    public function user()
    {
        return app('auth')->user();
    }

    /**
     * 自动实例化resource
     *
     * @param $model
     * @param string $scope Front或Admin
     * @return object
     */
    public function getResource($model, $scope = 'Front')
    {
        $basename = str_replace('Controller', '', class_basename($this)) . 'Resource';
        $className = "App\Http\Resources\\{$scope}\\{$basename}";

        try {
            return (new ReflectionClass($className))->newInstance($model);
        } catch (ReflectionException $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 自动执行resource的collection
     *
     * @param $list
     * @param string $scope Front或Admin
     * @return mixed
     */
    public function getCollection($list, $scope = 'Front')
    {
        $basename = str_replace('Controller', '', class_basename($this)) . 'Resource';
        $className = "App\Http\Resources\\{$scope}\\{$basename}";

        try {
            return (new ReflectionClass($className))
                ->getMethod('collection')
                ->invoke(null, $list);
        } catch (ReflectionException $e) {
            dd($e->getMessage());
        }
    }



    /**
     * 权限判断
     * @param $name
     * @return bool
     */
    public function hasPermission($name)
    {
        $role = $this->user()->role;
        if (!$role) {
            throw new AuthNoPermissionException('暂无权限');
        }
        if ($role->name == '超级管理员') {
            return true;
        }
        try {
            $permissions = $role->permissions->pluck('code')->toArray();
            // 查看交集
            if (count(array_intersect((array) $name, $permissions)) < 1) {
                throw new AuthNoPermissionException('暂无权限:' . $name);
            }
        } catch (\Exception $e) {
            throw new AuthNoPermissionException('暂无权限1:' . $e->getMessage());
        }
    }

}
